<?php

class Money_IndexController extends Core_Controller_Action_Standard {

    public function init() {
        if (!$this->_helper->requireUser()->isValid())
            return;
        $table = Engine_Api::_()->getDbtable('money', 'money');
        $table->insertUser();
    }


    public function sendAction() {
        if (!$this->_helper->requireUser()->isValid())
            return;

        $this->view->navigation = Engine_Api::_()->getApi('menus', 'core')
                ->getNavigation('money_main', array(), 'money_main_send');

        $this->view->form = $form = new Money_Form_Send();

        $moneyTable = Engine_Api::_()->getDbtable('money', 'money');
        $money = $moneyTable->getMoney();

        $this->view->money = $money;

        

        // Get params
        $amount = $this->_getParam('amount');
        $to = $this->_getParam('to');
        $body = $this->_getParam('body');
        $viewer = Engine_Api::_()->user()->getViewer();
        $toObject = null;
        
        // Build
        $isPopulated = false;
        if (!empty($to)) {
           
            // Prepopulate user
            $toUser = Engine_Api::_()->getItem('user', $to);
            $isMsgable = ( 'friends' != Engine_Api::_()->authorization()->getPermission($viewer, 'messages', 'auth') ||
                    $viewer->membership()->isMember($toUser) );
            if ($toUser instanceof User_Model_User &&
                    (!$viewer->isBlockedBy($toUser) && !$toUser->isBlockedBy($viewer)) &&
                    isset($toUser->user_id) &&
                    $isMsgable) {
                $this->view->toObject = $toObject = $toUser;
                $form->toValues->setValue($toUser->getGuid());
                $isPopulated = true;
            } else {
               
                $to = null;
            }
        } 
        $this->view->isPopulated = $isPopulated;
        
        if(!empty($amount)){
            $form->populate(array('amount'=>$amount));
        }
        
        if(!empty($body)){
            $form->populate(array('body'=>$body));
        }
        
        if (!$this->getRequest()->isPost()) {
            return;
        }

        if (!$form->isValid($this->getRequest()->getPost())) {
            return;
        }

        $table = Engine_Api::_()->getDbtable('transactions', 'money');

        $db = $table->getAdapter();
        $db->beginTransaction();
        try {
            // Prepopulated
            $values = $form->getValues();

            if ($toObject instanceof User_Model_User) {
                $recipientUser = $toObject;
                $recipients = $toObject;
                              
                // Validate friends
               
                    if (!$viewer->membership()->isMember($recipients)) {
                        return $form->addError('One of the members specified is not in your friends list.');
                    }
             
            } else if ($toObject instanceof Core_Model_Item_Abstract &&
                    method_exists($toObject, 'membership')) {
                $recipientUser = $toObject->membership()->getMembers();
                $recipients = $toObject;
            }
            // Normal
            else {
                $recipients = preg_split('/[,. ]+/', $values['toValues']);
                
                $recipients = array_unique($recipients);
              
                $recipients = array_slice($recipients, 0, $maxRecipients);
               
                $recipientsUsers = Engine_Api::_()->getItemMulti('user', $recipients);
                
               
                    foreach ($recipientsUsers as &$recipientUser) {
                        if (!$viewer->membership()->isMember($recipientUser)) {
                            return $form->addError('One of the members specified is not in your friends list.');
                        }
                    }
               
            }
            
            $trans = $table->sendMoney($recipientUser->getIdentity(), $values);

            $notifyApi = Engine_Api::_()->getDbtable('notifications', 'activity');

            $notifyApi->addNotification($recipientUser, $viewer, $trans, 'send_money', array(
                'count' => $values['amount']
            ));

            $db->commit();
        } catch (Exception $e) {
            $db->rollBack();
            throw $e;
        }

        return $this->_forward('success', 'utility', 'core', array(
            'messages' => array(Zend_Registry::get('Zend_Translate')->_('Your money is sent successfully.')),
            'parentRefresh' => true
        ));
    }

    public function transactionAction() {
        if (!$this->_helper->requireUser()->isValid())
            return;

        $this->view->navigation = Engine_Api::_()->getApi('menus', 'core')
                ->getNavigation('money_main', array(), 'money_main_transaction');

        $this->view->form = $form = new Money_Form_Admin_Search();
        $form->removeElement('text');

        $values = array();
        if ($form->isValid($this->_getAllParams())) {
            $values = $form->getValues();
            $this->view->formValues = array_filter($values);
        }

        foreach ($values as $key => $value) {
            if (null === $value) {
                unset($values[$key]);
            }
        }

        $viewer = Engine_Api::_()->user()->getViewer();

        $values['user_id'] = $viewer->getIdentity();
        
        $items_count = (int) Engine_Api::_()->getApi('settings', 'core')->getSetting('money.page', 30);
        
        $this->view->paginator = $paginator = Engine_Api::_()->getApi('core', 'money')->getTransactionPaginator($values);
        $paginator->setItemCountPerPage($items_count);
        $paginator->setCurrentPageNumber($this->_getParam('page', 1));
    }

    public function issueAction() {
        $this->view->navigation = Engine_Api::_()->getApi('menus', 'core')
                ->getNavigation('money_main', array(), 'money_main_issue');

        $this->view->form = $form = new Money_Form_Issue();
        $this->view->commission = $commission = Engine_Api::_()->getApi('settings', 'core')->getSetting('money.commissionissue');

        if (!$this->getRequest()->isPost() || !$form->isValid($this->getRequest()->getPost())) {
            return;
        }

        $table = Engine_Api::_()->getDbtable('issues', 'money');

        $values = $form->getValues();

        $db = $table->getAdapter();
        $db->beginTransaction();

        try {
            $issue = $table->createRow();
            $values['user_id'] = Engine_Api::_()->user()->getViewer()->getIdentity();
            
           
          
            $amount = round((($values['amount'] * $commission)/100) -  $values['amount'], 2);
            $values['amount'] = $amount;
            $issue->setfromArray($values);
            $issue->save();

            $db->commit();
        } catch (Exception $e) {
            $db->rollBack();
            throw $e;
        }
        
        return $this->_forward('success', 'utility', 'core', array(
            'messages' => array(Zend_Registry::get('Zend_Translate')->_('Your application was sent successfully.')),
             'parentRefresh' => true,
        ));
    }
    
    
   
}
